<template>
  <view class="content">
    <view class="tips-text">{{idcardInfos}}</view>
    <image class="finger-image" :src="fingerImgBase64" mode="aspectFit"></image>
    <image class="scanner-image" :src="scannerImgBase64" mode="aspectFit"></image>
    <image class="scanner-image2" :src="scannerImgBase64_2" mode="aspectFit"></image>
    <video class="video-record" ref="previewVideo" id="video" playsinline muted  
      :src-object.prop="stream" 
      :controls='false' 
      :show-play-btn='false' 
      :show-center-play-btn='false'>
    </video>
    
    <view class="btn" style="left: 100rpx;" @click="onBtnFingerPrint">获取指纹</view>
    <view class="btn" style="left: 400rpx;" @click="onBtnStartScannerPreview">打开扫描仪</view>
    <view class="btn" style="left: 700rpx;" @click="onBtnStopScannerPreview">关闭扫描仪</view>
    <view class="btn" style="left: 1000rpx;" @click="onBtnGetScannerImage">扫描仪拍照</view>
    <view class="btn" style="left: 1300rpx;" @click="onBtnGetIdCardInfo">读身份证</view>
    <view class="btn" style="left: 100rpx;top: 1200rpx;" @click="onBtnGetDeviceInfo">设备状态信息</view>
    <view class="btn" style="left: 400rpx;top: 1200rpx;" @click="onBtnStartVideoRecord">开始录像</view>
    <view class="btn" style="left: 700rpx;top: 1200rpx;" @click="onBtnStopVideoRecord">停止录像</view>
    <view class="btn" style="left: 1000rpx;top: 1200rpx;" @click="onBtnTestPlayVideo">测试数字人</view>
    <view class="btn" style="left: 1300rpx;top: 1200rpx;" @click="onBtnTestVideoChat">音视频通话</view>
    <view class="device-infos">{{deviceInfo}}</view>
    <audio
      id="audio" 
      autoplay
      playsinline
      style="width: 0; height: 0;"
    />
    
  </view>
</template>

<script>
  import { getStream } from '../../static/js/videoRecordH5.js' 
  import WebRTCSDK from '../../static/js/WebRTCSDK.js'
  var sdk      = null 
  var deviceId = 'device_xxx'
  var roomId   = 300 
  var callWait = false
  var inCall   = false 
  
  
  export default {
    data() {
      return {
        idcardInfos: '身份证信息:',
        fingerImgBase64: '',
        scannerImgBase64: '',
        scannerImgBase64_2: '',
        deviceInfo: '设备信息:', 
        stream: null,     // 摄像头流
      }
    },
    onLoad() {
      console.log('========================================= test ')
      var self = this 
      setTimeout(async ()=>{
         await self.test()
      }, 500)
      
      
    },
    methods: {
      onBtnFingerPrint() {
        var self = this 
        self.fingerImgBase64 = '' 
        window.api?.getFingerPrinter( res => {
          console.log('ui ----> getFingerPrinter, code: ' + res.code + ", base64_len: " + res.data.img_base64.length) 
          if (res.code == 200) {
            self.fingerImgBase64 = res.data.img_base64 
          }
        })
      },
      onBtnStartScannerPreview() {
        console.log('tttttttttttttttttttttttttttttttttttttttttttt')
        var self = this 
        window.api?.startScannerPreview( res => {
          console.log('ui ----> startScannerPreview, code:' + res.code) 
          if (res.code == 200 && res.data.img_base64) {
            self.scannerImgBase64 = `data:image/jpg;base64,${res.data.img_base64}`
          }
        })
      },
      onBtnStopScannerPreview() {
        window.api?.stopScannerPreview( res => {
          console.log('ui ----> stopScannerPreview' + JSON.stringify(res)) 
        })
      },
      onBtnGetScannerImage() {
        var self = this 
        window.api?.getScannerImage( res => {
          console.log('ui ----> getScannerImage', res.code, res.message) 
          if (res.code == 200) {
            self.scannerImgBase64_2 = `data:image/jpg;base64,${res.data.img_base64}`
          }
        })
      },
      onBtnGetIdCardInfo() {
        var self = this 
        window.api?.getIdCardInfo( res => {
          console.log('ui ----> getIdCardInfo, res: ' + JSON.stringify(res)) 
          self.idcardInfos = JSON.stringify(res.data)
        })
      },
      onBtnGetDeviceInfo() {
        var self = this 
        window.api?.getDeviceInfo( info => {
          console.log('ui ----> getDeviceInfo, code: ' + JSON.stringify(info)) 
          self.deviceInfo = info
        })
      },
      onBtnStartVideoRecord() {
        var self = this 
        
        window.api?.listenVideoRecording(res=>{
          console.log('---- ui, listenVideoRecording, res: ', JSON.stringify(res))
        })
        window.api?.startVideoRecord('hlb', 'M1234', (res=>{
          console.log('---- ui, startVideoRecord, res:', res)
          if (res.code == 200) {
            // 摄像头预览 
            // var stream = getStream() 
            // var video = document.querySelector('video');
            // if ("srcObject" in video) {
            //   video.srcObject = stream
            // } else {
            //   video.src = window.URL && window.URL.createObjectURL(stream) || stream 
            // }
            // video.play() 
          }
        })) 
      },
      onBtnStopVideoRecord() {
        window.api?.stopVideoRecord((res=>{
          console.log('---- ui, stopVideoRecord, res:', JSON.stringify(res))
        }))
      },
      onBtnTestPlayVideo() {
        console.log('================================ onBtnTestPlayVideo')
        window.api?.sceneLoanInfoPass( (res)=>{
          console.log('---ui:', JSON.stringify(res))
        })
      },
      initWetRtc() {
        if (!sdk) {
          console.log('================================ onBtnVideoChat')
          
          // 创建 SDK 实例
          sdk = new WebRTCSDK({
            signalingServer: 'wss://47.101.40.207:8299',
            debug: true,
            autoReconnect:true
          })
          
          // 连接信令服务器
          sdk.connect({
            cus_channel: '贵阳捷逸4S店一体机',
            cus_node: '补充流水'
          }, deviceId, roomId) 
          
          // 事件监听
          sdk.on('connected', () => {
            console.log('已连接到信令服务器')
          })
          sdk.on('disconnected', () => {
            console.log('与信令服务器断开连接')
          })
          sdk.on('peerJoined', (uid) => {
            console.log(`用户 ${uid} 加入`)
          })
          sdk.on('peerLeft', (uid) => {
            console.log(`用户 ${uid} 离开`)
          })
          sdk.on('callWait', () => {
            callWait = true
            setTimeout(() => { 
              if (callWait && !inCall) {
                sdk.endCall()
                console.log('无人接听')
                console.log(sdk)
              }
            }, 15000)
            console.log('等待通话接听')
          })
          // 通话事件
          sdk.on('callStarted', () => {
            callWait = false
            inCall = true
            console.log('通话已开始')
          })
          sdk.on('callEnded', () => {
            callWait = false
            inCall = false
            console.log('通话已结束')
          })
          sdk.on('error', ({ type, error }) => {
            console.error(`错误 [${type}]:`, error)
            if (type === 'offline') {
              console.log('对方不在线')
              sdk.endCall()
            }
          }) 
        }
      },
      onBtnTestVideoChat() {
        console.log('================================ onBtnVideoChat')
        
        // 开始通话
        sdk.startCall({ 
          order_id: 'xxx', // 订单号
          name: 'xxx', // 姓名，
          amount: 'xxx' // 融资额
        })
      },
      
      async test() {
        // navigator.mediaDevices.enumerateDevices()
        // .then((res) => {
          
        //   const cameras = res.filter((device) => device.kind === 'videoinput')
          
        //   console.log('==================================camera:', cameras.length)
        //   let result = cameras.map(d => d.getCapabilities()[0]?.facingMode)
        //   console.log(result)
          
        // })
        // .catch(err=>{
        //   console.log('[videoRecord] initCamera find camera error:')
        //   console.log(err) 
        // })
        
        // console.log('============================================================> h5 getUserMedia')
        // let stream = await navigator.mediaDevices.getUserMedia({
        //   audio: false, 
        //   video: { 
        //     width: 1280, 
        //     height: 720, 
        //     transform: 'scaleX(-1)', 
        //   },
        // }) 
        // const track = stream.getVideoTracks()[0];
        // // if (track) console.log('------------id:', (track.getSettings().deviceId)) 
      }
      
    }
    
    
  }
</script>

<style scoped>
  .content {
    width: 100vw;
    height: 100vh;
    position: relative;
  }
  .tips-text {
    width: 600rpx;
    height: 500rpx;
    word-wrap: break-word;
    position: absolute;
    left: 100rpx;
    top: 300rpx;
  }
  .finger-image {
    width: 80rpx;
    height: 120rpx;
    position: absolute;
    left: 350rpx;
    top: 100rpx;
    background-color: #f5f5f5;
  }
  
  .scanner-image {
    width: 400rpx;
    height:300rpx;
    position: absolute;
    left: 950rpx;
    top: 100rpx;
    background-color: #e7e7e7;
  }
  .scanner-image2 {
    width: 400rpx;
    height:300rpx;
    position: absolute;
    left: 1360rpx;
    top: 100rpx;
    background-color: #e7dbd7;
  }
  .video-record {
    width: 400rpx;
    height:300rpx;
    position: absolute;
    left: 1770rpx;
    top: 100rpx;
    background-color: #dfe5e7;
  }
  .btn {
    width: 200rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #00aaff;
    color: #fff;
    
    position: absolute;
    left: 200rpx;
    top: 1000rpx;
  }
  .device-infos {
    width: 600rpx;
    height: 500rpx;
    word-wrap: break-word;
    position: absolute;
    left: 2800rpx;
    top: 300rpx;
  }
</style>